﻿using System;
using System.Collections.Generic;
using System.Text;

namespace RuoTeng.Util.Update
{
    class UpdateConfig
    {
        static  private System.Xml.XmlDocument xml;
        static  private readonly string xmlFile = "update.xml";
        static private bool updateFile = false;
        protected static  bool Load()
        {
            try
            { 
                if (xml == null)
                {
                    updateFile = false;
                    xml = new System.Xml.XmlDocument();
                    xml.Load(xmlFile);
                    updateFile = true;
                }
                return updateFile;
            }
            catch (Exception)
            {
                return updateFile;
            }
        }

        public static bool IsLoad()
        {
            Load();
            return updateFile;
        }

        public static string GetValue(string name)
        {    
             try
             {
                 if (xml == null)
                 {
                     Load();
                 }
                string type = xml.DocumentElement.SelectSingleNode(name).InnerText;
                return type;
             }
              catch(Exception)
             {
                 return null;
              }
        }

        public static bool SetValue(string name, string value, bool aotoSave)
        {
            if (xml == null)
            {
                Load();
            }
        
            try
            {
                 System.Xml.XmlNode node = xml.DocumentElement.SelectSingleNode(name);
                  if (node == null)
                  {   
                      System.Xml.XmlNode root = xml.SelectSingleNode("Update");
                      System.Xml.XmlElement xe = xml.CreateElement(name);
                      xe.InnerText =  value;
                      root.AppendChild(xe);
                   }
                  else
                  {
                      node.InnerText =value;
                  }
                  if(aotoSave)
                  {
                     xml.Save("update.xml");
                  }               
                  return true;
                }
                catch (Exception)
                {
                    return false;
                }
            }

        public static bool SetValue(string name, string value)
        {
            return SetValue(name,value,true);
        }

    }
}
